<?php

namespace app\api\controller;

use think\Db;
use fast\Random;
use think\Validate;
use app\common\library\Ems;
use app\common\library\Sms;
use app\api\controller\Wallet;
use app\common\controller\Api;
use app\admin\model\QianbaoSysetmLog;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    private function index()
    {
        $this->success('', 'welcome');
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $wallet = new  Wallet();
            $wallet->wallet_user();

            // $data = ['userinfo' => $this->auth->getUserinfo()];
            $data = $this->auth->getUserinfo();
            $this->success(__('Logged in successful'), $data['token']);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     */
    public function getuserinfo()
    {
        $user = $this->auth->getuser();
        // 更新vip等级
        users_vip($user);
        //如果已经有账号则直接登录
        $ret = $this->auth->direct($user->id);
        $userinfo = $this->auth->getUserinfo();
        $userinfo['packet'] = 0;
        // 红包
        // if($this->packet($user)){
        //     $userinfo['packet'] = 1;
        // }else{
        //     $userinfo['packet'] = 0;
        // }

        $this->success('', ['userinfo' => $userinfo]);
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            // $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $secpwd   支付密码
     * @param string $tjm   推荐码
     * @param string $mobile   手机号
     * @param string $code   验证码

     */
    public function register()
    {
        $username = $this->request->request('username');
        $email = $this->request->request('email');

        $password = $this->request->request('password');
        $mobile = $this->request->request('mobile');
        $secpwd = $this->request->request('secpwd');
        $code = $this->request->request('code');
        $tjm = $this->request->request('tjm');
        $extend = [];

        if (!$password) {
            $this->error(__('登录密码不能为空'));
        }
        if (!$secpwd) {
            $this->error(__('支付密码不能为空'));
        }

        if (strlen($secpwd) != 6) {
            $this->error(__('支付密码为6位'));
        }
        if (!Validate::regex($username, "^(?![^a-zA-Z]+$)(?!\D+$).{4,10}$")) {
            $this->error(__('用户名必须字母加数字4-10位'));
        }

        // if ($email && !Validate::is($email, "email")) {
        //     $this->error(__('Email is incorrect'));
        // }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Validate::regex($password, "^(?![^a-zA-Z]+$)(?!\D+$).{8,16}$")) {
            $this->error(__('密码必须字母加数字8-16位'));
        }


        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }


        //推荐人暂时不开启
        $tjm = isset($tjm) ? $tjm : '';
        if ($tjm) {
            // 获取推荐码用户信息
            $tjr = userinfotjm($tjm);
            if (!$tjr) {
                $this->error(__('推荐码不正确'));
            }
            $extend['tid'] = $tjr['id'];
            $extend['tname'] = $tjr['username'];
            $extend['tpath'] = $tjr['tpath'] . ',' . $tjr['id'];
            $extend['secpwd'] = md5($secpwd);
            //  目前弃用
            // if(!direct_push($tjr)){
            //     $this->error('系统错误');
            // }
        } else {
            $this->error('推荐码不能为空');
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, $extend);
        if ($ret) {
            // $data = ['userinfo' => $this->auth->getUserinfo()];
            $user = $this->auth->getUser();
            $user->tjm = authcodenum($user['id'], 'code');
            $user->save();
            $data = $this->auth->getUserinfo();
            $this->success(__('Sign up successful'), $data['token']);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员头像
     *
     * @param file $file 昵称
     */
    public function avatar()
    {
        $avatar =  action('api/common/upload');
        $user = $this->auth->getUser();
        // $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $user->avatar = $avatar['url'];
        $user->save();
        $this->success('修改成功');
    }



    /**
     * 修改会员个人信息
     *
     * @param string $username 用户名
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        if (!Validate::regex($username, "^(?![^a-zA-Z]+$)(?!\D+$).{4,10}$")) {
            $this->error(__('必须字母加数字4-10位'));
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exist'));
            }
            $user->username = $username;
        }
        $user->save();
        $this->success('修改成功');
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('修改手机号成功');
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 修改登录密码
     * @param string $oldpassword           旧密码
     * @param string $newpassword           新密码
     * @param string $confirmnewpassword   确认新密码
     * @return boolean
     */
    public function changepwd()
    {
        $newpassword = $this->request->request('newpassword');
        $confirmnewpassword = $this->request->request('confirmnewpassword');
        $oldpassword = $this->request->request('oldpassword');

        if (empty($oldpassword) || empty($newpassword) || empty($confirmnewpassword)) {
            $this->error(__('缺少必要的参数'));
        }

        if (!Validate::regex($newpassword, "^(?![^a-zA-Z]+$)(?!\D+$).{8,16}$")) {
            $this->error(__('密码必须字母加数字8-16位'));
        }
        if ($newpassword <> $confirmnewpassword) {
            $this->error(__('两次输入密码不一致'));
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword);
        if ($ret) {
            $this->auth->logout();
            $this->success(__('修改密码成功,需要重新登录'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 重置密码/忘记密码
     *
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {   
        
        if(!$this->auth->mobile){
            $username = $this->request->request("username");
            if(!$username){
                $this->error('用户名不能为空');
            }
            $mobile = db('user')->where('username',$username)->value('mobile');
            if(!$mobile){
                $this->error('用户名不存在');
            }
        }else{
            $mobile = $this->auth->mobile;
        }
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (!Validate::regex($newpassword, "^(?![^a-zA-Z]+$)(?!\D+$).{8,16}$")) {
            $this->error(__('密码必须字母加数字8-16位'));
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改安全密码
     * @author zly
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     * @param string $confirmnewpassword 确认新密码
     */

    public function changesecpwd()
    {
        $newpassword = $this->request->request('newpassword');
        $confirmnewpassword = $this->request->request('confirmnewpassword');
        $oldpassword = $this->request->request('oldpassword');

        if (empty($oldpassword) || empty($newpassword) || empty($confirmnewpassword)) {
            $this->error(__('Invalid parameters'));
        }

        if (strlen($newpassword) < 6) {
            $this->error(__('密码最少6位'));
        }

        if ($newpassword <> $confirmnewpassword) {
            $this->error(__('两次输入密码不一致'));
        }

        $user = $this->auth->getUser();
        if ($user['secpwd'] != md5($oldpassword)) {
            $this->error(__('安全密码错误'));
        }
        $user->secpwd = md5($newpassword);
        $user->updatetime = time();
        $ret = $user->save();
        if ($ret) {
            $this->success(__('修改安全密码成功'));
        } else {
            $this->error(__('修改安全密码失败'));
        }
    }


    /**
     * 重置支付密码
     * @author zly
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */

    public function resetsecpwd()
    {
        $mobile = $this->auth->mobile;
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (strlen($newpassword) < 6) {
            $this->error(__('密码最少6位'));
        }


        $ret = Sms::check($mobile, $captcha, 'secpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'secpwd');

        $user = $this->auth->getUser();
        $user->secpwd = md5($newpassword);
        $user->updatetime = time();
        $ret = $user->save();
        if ($ret) {
            $this->success(__('重置支付密码成功'));
        } else {
            $this->error(__('重置支付密码失败'));
        }
    }

    /**
     * 邀请好友
     *
     */
    public function invite()
    {
        $data['code_img'] = request()->domain() . '/' . getcode(config('register') . $this->auth->tjm, true,$this->auth->tjm);
        $data['invite_code'] = $this->auth->tjm;
        $this->success('', $data);
    }

    // 判断是否满足领取红包要求
    private function packet($user)
    {   
        $config = config('site');
        // $users_count = db('user')->where('tid',$user['id'])->where('usdt','>=',10)->where('order_sum','>',0)->count();
        // if(!$users_count){
        //     return false;
        //     // $this->error('没有满足条件无法抢购红包');
        // }
        $orders_count = db('qianbao_sysetm_log')->where('uid',$user['id'])->where('type',10)->whereTime('createtime','today')->count();
        
        $users_count = db('user')->where('tid',$user['id'])->whereTime('createtime','today')->count();
        
        if($orders_count >= $config['frequency'] + $users_count*$config['frequency']){
            return false;
            // $this->error('今日次数已用完');
        }

        return true;
    }

    /**
     * 添加充币地址
     *
     * @param string $address 充币地址
     */
    public function address()
    {   
        $address = $this->request->request("address");

        if(!$address){
            $this->error('你输入你的充币地址绑定');
        }
        $user = $this->auth->getUser();
        if($user['address'] == $address){
            // $this->error('你已绑定地址,无需在绑定');
            $this->error('请勿重复绑定');
        }
        $user->address = $address;
        $user->save();
        $this->success('绑定成功');
    }

}
